package com.gengzp.rpc.controller;

import com.gengzp.rpc.core.RpcProducerCoreFunc;
import com.gengzp.rpc.exception.RpcException;
import com.gengzp.rpc.model.common.req.RpcRequest;
import com.gengzp.rpc.model.common.resp.RpcResponse;
import com.gengzp.rpc.model.remoteTransaction.req.RpcRollbackRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.gengzp.rpc.constants.RpcUriConstants.*;

/**
 * @ClassName RpcProducerController
 * @Description 远程调用生产者控制器
 * @Author gengzp
 * @Date 2025/8/20 15:42
 */
@RestController
@RequestMapping(RPC_PRODUCER_CONTROLLER_URI)
public class RpcProducerController {

    private static final Logger logger = LoggerFactory.getLogger(RpcProducerController.class);

    @Autowired
    private RpcProducerCoreFunc rpcProducerCoreFunc;

    /**
     * 生产者远程调用方法执行接口
     */
    @PostMapping(RPC_PRODUCER_METHOD_URI)
    public RpcResponse<?> doRequest(@RequestBody RpcRequest req) {
        try {
            logger.info("[Producer] 接收远程调用, 调用者服务名: {}, 调用方法: {}.{}(), 请求唯一标识: {}",
                    req.getConsumerServiceName(), req.getInterfaceClass().getSimpleName(), req.getMethodName(), req.getRequestId());

            // 执行核心生产者逻辑
            RpcResponse<?> result = rpcProducerCoreFunc.doExecuteRemoteCallProducer(req);

            logger.info("[Producer] 远程调用执行完成");
            return result;
        } catch (RpcException e) {
            logger.error("[Producer] 远程调用执行失败, 失败信息: {}", e.getMessage(), e);
            return RpcResponse.fail(e.getMessage(), req.getEnableRemoteTransactionFlag());
        }
    }

    /**
     * 生产者回滚方法执行接口
     */
    @PostMapping(RPC_PRODUCER_ROLLBACK_METHOD_URI)
    public RpcResponse<?> doRollback(@RequestBody RpcRollbackRequest req) {
        try {
            logger.info("[Producer] 执行回滚逻辑, 调用方法: {}.{}(), 请求唯一标识: {}",
                    req.getInterfaceName(), req.getMethodName(), req.getRequestId());

            RpcResponse<?> result = rpcProducerCoreFunc.doRemoteTransactionRollback(req);

            logger.info("[Producer] 回滚方法执行完成");
            return result;
        } catch (RpcException e) {
            logger.error("[Producer] 回滚方法执行失败, 失败信息: {}", e.getMessage(), e);
            return RpcResponse.fail(e.getMessage(), true);
        }
    }

}
